package generator;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;


/**
 * @author badqiu
 * @email badqiu(a)gmail.com
 */
public class PropertiesProvider {


    private PropertiesProvider() {
    }

    public static Map loadPropertiesToMap(String fileName) {
        try {
            Properties props = loadProperties(fileName);
            Map map = new HashMap();
            for (Iterator it = props.entrySet().iterator(); it.hasNext(); ) {
                Map.Entry entry = (Map.Entry) it.next();
                map.put(str2Trim(entry.getKey()), str2Trim(entry.getValue()));
            }
            return map;
        } catch (IOException e) {
            throw new RuntimeException("Load Properties error", e);
        }
    }


    public static String str2Trim(Object s) {
        if (s instanceof String) {
            return ((String) s).trim();
        }
        throw new RuntimeException(s + "is not String Object");
    }

    public static Properties loadProperties(String resourceName) throws IOException {
        Properties properties = new Properties();
        Enumeration urls = PropertiesProvider.class.getClassLoader().getResources(resourceName);
        while (urls.hasMoreElements()) {
            URL url = (URL) urls.nextElement();
            InputStream is = null;
            try {
                URLConnection con = url.openConnection();
                con.setUseCaches(false);
                is = con.getInputStream();
                properties.load(is);
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
        return properties;
    }
}
